<?php

declare(strict_types=1);

namespace App\Task;

use App\Model\AftersaleProduct;
use App\Model\AppUserCashAccount;
use App\Model\FlyOrderCommission;
use App\Service\AdvanceWithdrawService;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;

/**
 * 超过售后服务期限后对用户分销产品提现进行结算
 * Class SettleAccountsTask
 * @package App\Task
 */
class SettleAccountsTask
{
    public function execute(): void
    {
        // 查询所有已过售后期的，剩余未退的，（点餐 未退数量大于0的）所有商品金额
        $products = FlyOrderCommission::query()
            ->leftJoin('fly_order_product', 'fly_order_commission.op_id', '=', 'fly_order_product.id')
            ->leftJoin('fly_order', 'fly_order_product.order_id', '=', 'fly_order.id')
            ->where([
                'is_pay' => 1,
                'paid_price' => 0
            ])
            ->whereIn('order_status', [2, 3])
            ->whereIn('order_type', [1, 3]) // 仅限有商品的订单
            ->where('free_num', '>', 0)
            ->where(function ($where) {
                $where->whereRaw('can_af_apply_duration*86400+paid_time<' . time()) // 超过售后期限
                ->orWhereRaw('can_af_apply_duration=-1 and paid_time+86400*7<' . time());// 无售后期限售后、美食点餐分销商品 超过7天资金锁定期
            })->select(['fly_order.user_id', 'fly_order_commission.user_id', 'fly_order_commission.id', 'fly_order_commission.commission_rate', 'fly_order_product.single_price', 'free_num', 'fly_order_commission.order_id', 'fly_order_commission.order_sku_id'])
            ->get();
        $order_can_check = empty($products) ? [] : $products->toArray();
        Db::beginTransaction();
        try {
            foreach ($order_can_check as $value) {
                // 过滤在此期间还仍处于售后中的商品
                $af_check = AftersaleProduct::query()
                    ->leftJoin('fly_aftersale', 'fly_aftersale_products.af_id', '=', 'fly_aftersale.af_id')
                    ->whereIn('af_status', [1, 2])// 进行中的售后单
                    ->where(['fly_aftersale.order_id' => $value['order_id'], 'fly_aftersale_product.sku_id' => $value['order_sku_id'], 'fly_aftersale.user_id' => $value['user_id']])
                    ->exists();
                if ($af_check) {
                    continue;
                }
                // 结算商品提成
                FlyOrderCommission::where(['id' => $value['id']])->update([
                    'get_subtotal' => $value['single_price'] * $value['free_num'] * $value['commission_rate'],// 退款后剩余可结算数量
                    'cash_has_merge' => 1
                ]);
                if (!AppUserCashAccount::where([
                    'user_id' => $value['user_id'],
                    'account_type' => AdvanceWithdrawService::TYPE_USER
                ])->exists()) {
                    // 创建资金账户
                    AppUserCashAccount::where([
                        'user_id' => $value['user_id'],
                        'account_type' => AdvanceWithdrawService::TYPE_USER
                    ])->insert([
                        'user_id' => $value['user_id'],
                        'amount_total_in' => $value['single_price'] * $value['free_num'] * $value['commission_rate'],
                        'account_type' => AdvanceWithdrawService::TYPE_USER,
                        'create_time' => time(),
                        'surplus' => $value['single_price'] * $value['free_num'] * $value['commission_rate'],
                    ]);
                } else {
                    // 更新资金账户
                    AppUserCashAccount::where([
                        'user_id' => $value['user_id'],
                        'account_type' => AdvanceWithdrawService::TYPE_USER
                    ])->update([
                        'amount_total_in' => Db::raw("amount_total_in+" . $value['single_price'] * $value['free_num'] * $value['commission_rate']), // ·累计入账金额
                        'account_type' => AdvanceWithdrawService::TYPE_USER,
                        'create_time' => time(),
                        'surplus' => Db::raw("surplus+" . $value['single_price'] * $value['free_num'] * $value['commission_rate']),// 增加剩余余额
                    ]);
                }
            }
        } catch (\Throwable $exception) {
            echo $exception->getMessage();
            Db::rollBack();
        }
        Db::commit();
    }
}